<template>
  <view class="content">
    <view class="small-text">将自动连接名称为 {{printerName}} 的打印机</view>
    <view class="text-area">
      <view class="mt-1">
        <button type="default" @click="print()">打印测试</button>
      </view>
      <view class="mt-1">
        <button type="default" @click="printText()">打印文字</button>
      </view>
      <view class="mt-1">
        <button type="default" @click="printQrcode()">打印二维码</button>
      </view>
      <view class="mt-1">
        <button type="default" @click="printBar()">打印条码</button>
      </view>
    </view>
  </view>
</template>

<script>
  import BluetoothPrinter from '@/uni_modules/chuangyin-bluetooth/utils/bluetooth_printer.js'
  import PrintCPCL from '@/uni_modules/chuangyin-bluetooth/utils/print_cpcl.js'

  export default {
    data() {
      return {
        printerName: ''
      }
    },

    onShow() {
      this.printer = new BluetoothPrinter(uni)
      this.printerName = uni.getStorageSync('printerName')

      const items = uni.getStorageSync('items') || {}
      items.cpcl = this.printerName
      uni.setStorageSync('items', items)
      console.debug('items', uni.getStorageSync('items'))

      this.printer.registeredDevices = [this.printerName]
    },
    
    onUnload() {
      this.printer.closeBLEConnection()
    },

    methods: {

      print() {
        const cpcl = new PrintCPCL()
        cpcl.text_bold('hello, world!')
        cpcl.text('欢迎使用蓝牙打印机！')
        cpcl.qrcode_right('https://one.work')
        cpcl.barcode('123456789')
        
        this.printer.getState({
          success: (res) => {
            this.printer.writeValue(cpcl.render())
          }  
        })
      },

      printText() {
        const cpcl = new PrintCPCL()
        cpcl.text_bold('hello, world!')
        cpcl.text('欢迎使用蓝牙打印机！')
        
        this.printer.getState({
          success: (res) => {
            this.printer.writeValue(cpcl.render())
          }  
        })
      },

      printQrcode() {
        const cpcl = new PrintCPCL()
        cpcl.qrcode_right('https://one.work')
        
        this.printer.getState({
          success: (res) => {
            this.printer.writeValue(cpcl.render())
          }  
        })
      },

      printBar() {
        const cpcl = new PrintCPCL()
        cpcl.barcode('123456789')

        this.printer.getState({
          success: (res) => {
            this.printer.writeValue(cpcl.render())
          }  
        })
      }

    }
  }
</script>

<style>
  .content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .text-area {
    margin-top: 0.75rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  
  .small-text {
    font-size: 0.8rem;
    text-align: center;
    margin-top: 0.75rem;
    color: #999;
  }
  
  .mt-1 {
    margin-top: 0.75rem;
  }

</style>
